import { createStore } from 'vuex'
import WebsocketUtil from "@/utlis/websocket"

//创建一个仓库
export default new createStore({
	//全局状态
	state: {
		//用户
		user: uni.getStorageSync('user'),
		//token
		token: uni.getStorageSync('token'),
		// websocket
		websocket: null
	},
	//获取数据
	getters: {

	},
	//修改状态
	mutations: {

		//保持token
		setToken(state, data) {
			state.token = data;
			uni.setStorageSync('token', data);
		},

		//保存用户
		setUser(state, data) {
			state.user = data;
			uni.setStorageSync('user', data);
		},

		//清除token
		resetToken(state) {
			state.token = '';
			uni.removeStorageSync('token');
		},

		//清除用户
		resetUser(state) {
			state.user = {};
			uni.removeStorageSync('user');
		},

		//清除所有
		resetAllState(state) {
			state.token = null;
			state.user = null;
			uni.removeStorageSync('token');
			uni.removeStorageSync('user');
		},
		//创建socket连接K
		initSocket(state) {
			if (state.websocket?.socketTask) return;
			state.websocket = new WebsocketUtil("ws://192.168.101.83:8080/websocket/" + state
				.user.userId)

			// setTimeout(() => {
			// 	state.websocket?.socketTask && state.websocket.onMessage(data => {
					
			// 	})
			// }, 2000)
		},

		//获取
		getSocket(state) {
			if (!state.websocket) commit("initSocket")
			return state.websocket
		},
		//清除socket
		clearrSocket(state) {
			state.websocket = null
		},
		//关闭socket
		closeSocket(state) {
			state.websocket.closeSocket()
		}
	},
	//异步修改
	actions: {

	}
})